package com.example.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.CoSensor;
import com.example.entity.FlameSensor;
import com.example.entity.Params;
import com.example.repository.FlameSensorMapper;
import com.example.util.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class FlameSensorService extends ServiceImpl<FlameSensorMapper, FlameSensor> {

    @Resource
    private FlameSensorMapper flameSensorMapper;


    public PageInfo<FlameSensor> getSensorData(Params params) {
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<FlameSensor> search = flameSensorMapper.getSensorData();
        return PageInfo.of(search);
    }

    public double getFire() {
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.MINUTE, -20);
        Date twentySecondsAgo = calendar.getTime();
        return flameSensorMapper.selectList(Wrappers.<FlameSensor>lambdaQuery().between(
                        FlameSensor::getCreateTime, DateUtil.date2Str(twentySecondsAgo), DateUtil.date2Str(now)))
                .stream().mapToInt(FlameSensor::getFire).average().orElse(0);
    }

    public void addFS(FlameSensor flameSensor) {
        flameSensorMapper.insert(flameSensor);
    }

    public void deleteFS(Long id) {
        flameSensorMapper.deleteById(id);
    }


}
